package org.example.newcoder_summer.Controller;

import org.example.newcoder_summer.pojo.Result;
import org.example.newcoder_summer.pojo.User;
import org.example.newcoder_summer.service.UserService;
import org.example.newcoder_summer.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        User u = userService.login(user);
        if(u != null){
            Map<String,Object> claims = new HashMap<>();
            claims.put("id",u.getId());
            claims.put("identity",u.getIdentity());
            claims.put("account",u.getAccount());
            claims.put("userName",u.getUserName());
            claims.put("password",u.getPassword());

            String jwt = JwtUtils.generateToken(claims);
            return Result.success(jwt);
        }
        return Result.error("用户名或密码错误");
    }

    @PostMapping("/register")
    public Result register(@RequestBody User user) {
        //后端校验
        if(user.getUserName() == null){
            return Result.error("userName");
        }
        if(user.getPassword() == null){
            return Result.error("password");
        }
        if(user.getPhoneNumber() == null){
            return Result.error("phoneNumber");
        }
        if(user.getPhoneNumber().length() != 11){
            return Result.error("phoneNumberLength");
        }
        if(user.getGender() == 0){
            return Result.error("gender");
        }
        userService.save(user);
        return Result.success(user);
    }
}
